package io.github.eric.urpc.example.test;

import io.github.eric.urpc.core.conn.ConnectionListener;
import io.github.eric.urpc.core.rpc.RpcContext;
import io.github.eric.urpc.core.rpc.RpcController;
import io.github.eric.urpc.core.rpc.RpcMethod;
import io.github.eric.urpc.example.msg.EchoMsg;
import io.github.eric.urpc.example.msg.PingRequest;
import io.github.eric.urpc.example.msg.PingResponse;
import io.github.eric.urpc.server.Server;
import io.github.eric.urpc.server.ServerConfig;
import io.github.eric.urpc.server.ServerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class MockServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(MockServer.class);
    private Server server;

    public MockServer(ConnectionListener... connectionListeners) {
        // init config
        ServerConfig serverConfig = getBuilder()
                .build();
        if (connectionListeners != null && connectionListeners.length > 0) {
            ((ServerContext)serverConfig).addConnectionListeners(Arrays.asList(connectionListeners));
        }
        // init server
        server = new Server(serverConfig);
    }



    private static ServerConfig.Builder getBuilder() {
        return new ServerConfig.Builder()
//                .nettyLoggingLevel(LogLevel.INFO)
                .applicationName("mockServer")
                .listenPort(52379)
                .heartBeatTimeout(15)
                .ordered(true)
                // set controllers
                .rpcControllers(Collections.singletonList(new RpcController() {
                    @RpcMethod
                    public EchoMsg onEchoMessage(EchoMsg msg) {
                        LOGGER.info("Server receive a TestMessage, msg: {}, sendAt: {}, and resend it to client", msg.getMsg(), msg.getSendAt());
                        return msg;
                    }

                    @RpcMethod
                    public PingResponse onPingRequest(PingRequest pingRequest, RpcContext rpcContext) {
                        LOGGER.info("Server receive a PingRequest from {}, and send response to client after 3 seconds", rpcContext.getRemoteAddress());
                        return new PingResponse();
                    }
                }));
    }

    public void start() {
        server.start();
    }

    public void shutdown() {
        server.shutdown();;
    }

    public Server getServer() {
        return server;
    }

    public static void main(String[] args) {
        MockServer simpleServer = new MockServer();
        simpleServer.start();
    }
}
